import sys
import os
import datetime
from dateutil.parser import parse
import time
import queue
import signal
import threading as th
import eii.msgbus as mb
from argparse import ArgumentParser, SUPPRESS

usage_text = \
"""
Usage:
    For IPC:
        sudo python3 msg_transfer_station.py ipc <topic>
    For TCP:
        sudo python3 msg_transfer_station.py tcp <topic> <ip> <port>
"""

msg_queue = queue.Queue(maxsize=10)
msgbus_cfg_sub_ipc = {"type": "zmq_ipc", "socket_dir": "/opt/intel/eii/sockets"}
topic_sub = "pcb_camera1_stream"

# Publisher config
msgbus_cfg_pub = {"type": "zmq_tcp", "zmq_tcp_publish": {"host": "0.0.0.0", "port": 55005}}
topic_pub = "transfer_station"

publisher = None
subscriber = None
exit_now = False


def msg_publish(msgbus_cfg, topic):
    global exit_now
    global publisher
    global msg_queue
    msgbus = mb.MsgbusContext(msgbus_cfg)
    publisher = msgbus.new_publisher(topic)
    first_empty_flag = True
    first_empty_time = 0

    while not exit_now:
        if not msg_queue.empty():
            first_empty_flag = True
            first_empty_time = 0
            metadata, blob = msg_queue.get_nowait()
            publisher.publish((metadata, blob))
        else:
            if first_empty_flag:
                first_empty_time = parse(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                first_empty_flag = False
            c1 = parse(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            lapsed = (c1 - first_empty_time).total_seconds()
            if lapsed > 3.0:
                print(lapsed)
                publisher.publish((static_metadata, static_blob))
            time.sleep(0.02)


def msg_subscribe(msgbus_cfg, topic):
    global exit_now
    global subscriber
    global msg_queue
    msgbus = mb.MsgbusContext(msgbus_cfg)
    subscriber = msgbus.new_subscriber(topic)

    try:
        while not exit_now:
            metadata, blob = subscriber.recv()
            msg_queue.put((metadata, blob))
    except SystemExit:
        pass
    finally:
        if subscriber:
            subscriber.close()
            subscriber = None


def signal_handler(sig, frame):
    global publisher
    global subscriber
    global exit_now
    exit_now = True
    if publisher:
        publisher.close()
        publisher = None
    sys.exit(0)


if __name__ == "__main__":
    if len(sys.argv) == 3 and sys.argv[1] == "ipc":
        msgbus_cfg_sub = msgbus_cfg_sub_ipc
        topic_sub = sys.argv[2]
    elif len(sys.argv) == 5  and sys.argv[1] == "tcp":
        topic_sub = sys.argv[2]
        msgbus_cfg_sub = {
            "type": "zmq_tcp", 
            topic_sub: {
                "host": sys.argv[3], 
                "port": int(sys.argv[4])
            }
        }
    else:
        print(usage_text)
        sys.exit(1)
        
    static_metadata = {'frame_number': 12, 'channels': 3, 'encoding_type': 'jpeg', 'height': 1940, 'img_handle': '708496bc5e', 'defects': [], 'width': 2588, 'encoding_level': 95}
    pwd_path = os.path.abspath(os.path.dirname(__file__))
    static_img_path = pwd_path + "/disconnect.jpg"
    with open(static_img_path, 'rb') as f:
        static_blob = f.read()

    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGQUIT, signal_handler)

    thread_pub = th.Thread(target=msg_publish, args=(msgbus_cfg_pub, topic_pub))
    thread_pub.daemon = True
    thread_pub.start()

    thread_sub = th.Thread(target=msg_subscribe, args=(msgbus_cfg_sub, topic_sub))
    thread_sub.daemon = True
    thread_sub.start()

    thread_pub.join()
    thread_sub.join()
